package com.markhsiu.MiniMQ.broker.message;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.markhsiu.MiniMQ.model.Message;
import com.markhsiu.MiniMQ.model.Result;

/**
 * Created by Mark Hsiu on 2017/2/9.
 */
public class BrokerFactory {

    /**
     * 回调消息缓存
     */
    private final Map<String,Result> callBackMap = new ConcurrentHashMap<String, Result>();
 
    /**
     * 消息存储
     */
    private final Map<String,Queue<Message>> messageStore = new ConcurrentHashMap<>();

    private final static BrokerFactory factory = new BrokerFactory();
    private BrokerFactory(){ }
    
    public static BrokerFactory instance(){
    	return factory;
    }
    
    public  void putCallBack(String messageID,Result result){
        callBackMap.put(messageID,result);
    }

    public  Result getCallBack(String messageID){
        return callBackMap.get(messageID);
    }
    
    
    public void addMessage(Message e){
    	Queue<Message> topciQueue = messageStore.get(e.getTopic());
    	if(topciQueue == null){
    		topciQueue = new ConcurrentLinkedQueue<Message>();
    		messageStore.put(e.getTopic(), topciQueue);
    	}
    	topciQueue.add(e);
    	System.out.println("topic : " + e.getTopic() + " == "+ topciQueue.size());
    }
    
    public Message pollMessage(String topic){
    	Queue<Message> topciQueue = messageStore.get(topic);
    	if(topciQueue != null){
    		return topciQueue.poll();
    	}
    	return null;
    }
    

}
